package com.feng.gulimall.ware.service.impl;

import com.alibaba.nacos.api.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.feng.common.utils.R;
import com.feng.gulimall.ware.feign.ProductFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.feng.common.utils.PageUtils;
import com.feng.common.utils.Query;

import com.feng.gulimall.ware.dao.WareSkuDao;
import com.feng.gulimall.ware.entity.WareSkuEntity;
import com.feng.gulimall.ware.service.WareSkuService;
import org.springframework.transaction.annotation.Transactional;


@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {

    @Autowired
    private ProductFeign productFeign;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        String skuId = (String) params.get("skuId");
        String wareId = (String) params.get("wareId");

        LambdaQueryWrapper<WareSkuEntity> wrapper = new LambdaQueryWrapper<>();
        if (!StringUtils.isBlank(skuId)){
            wrapper.eq(WareSkuEntity::getSkuId, skuId);
        }
        if (!StringUtils.isBlank(wareId)){
            wrapper.eq(WareSkuEntity::getWareId, wareId);
        }

        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void updateStock(Integer stock, Long skuId, Long wareId) {
        // 查询是否存在当前库存信息
        List<WareSkuEntity> wareSkuEntities = baseMapper.selectList(new LambdaQueryWrapper<WareSkuEntity>()
                .eq(WareSkuEntity::getSkuId, skuId).eq(WareSkuEntity::getWareId, wareId));
        if (wareSkuEntities == null || wareSkuEntities.size() == 0){
            // 没有则添加
            WareSkuEntity wareSkuEntity = new WareSkuEntity();
            wareSkuEntity.setSkuId(skuId);
            wareSkuEntity.setWareId(wareId);
            wareSkuEntity.setStock(stock);
            wareSkuEntity.setStockLocked(0);
            R info = productFeign.info(skuId);
            Map<String, Object> skuInfo = (Map<String, Object>) info.get("skuInfo");
            wareSkuEntity.setSkuName((String) skuInfo.get("skuName"));
            this.save(wareSkuEntity);
        }else {
            // 有，修改

            // update x set
            WareSkuEntity wareSkuEntity = new WareSkuEntity();
            wareSkuEntity.setStock(stock + wareSkuEntities.get(0).getStock());
            wareSkuEntity.setId(wareSkuEntities.get(0).getId());
            baseMapper.updateById(wareSkuEntity);

        }


    }

}
